import type { PageResult, PageParams, BaseResponse } from '@/types/api.d'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'

/**
 * 医生信息类型定义
 */
export interface Doctor {
  id: number
  doctorCode: string
  doctorName: string
  deptId: number
  title?: string
  specialty?: string
  hospitalId: number
  delFlag: 'Y' | 'N'
  createTime: string
  updateTime: string
}

/**
 * 医生查询参数
 */
export interface DoctorSearchParams extends PageParams {
  doctorName?: string
  doctorCode?: string
  deptId?: number
  hospitalId?: number
  delFlag?: 'Y' | 'N'
}

/**
 * 获取医生列表
 * @param params 查询参数
 * @returns 分页结果
 */
export const fetchDoctors = async (params: DoctorSearchParams): Promise<PageResult<Doctor>> => {
  try {
    const { data } = await request.get<BaseResponse<PageResult<Doctor>>>('/api/doctors', { params })
    return data.data
  } catch (error) {
    ElMessage.error('获取医生列表失败')
    throw error
  }
}

/**
 * 获取医生详情
 * @param id 医生ID
 * @returns 医生详情
 */
export const getDoctor = async (id: number): Promise<Doctor> => {
  try {
    const { data } = await request.get<BaseResponse<Doctor>>(`/api/doctors/${id}`)
    return data.data
  } catch (error) {
    ElMessage.error('获取医生详情失败')
    throw error
  }
}

/**
 * 创建医生
 * @param data 医生数据
 * @returns 创建的医生信息
 */
export const createDoctor = async (data: Omit<Doctor, 'id'>): Promise<Doctor> => {
  try {
    const { data: response } = await request.post<BaseResponse<Doctor>>('/api/doctors', data)
    ElMessage.success('创建医生成功')
    return response.data
  } catch (error) {
    ElMessage.error('创建医生失败')
    throw error
  }
}

/**
 * 更新医生
 * @param data 医生数据
 * @returns 更新后的医生信息
 */
export const updateDoctor = async (data: Doctor): Promise<Doctor> => {
  try {
    const { data: response } = await request.put<BaseResponse<Doctor>>(`/api/doctors/${data.id}`, data)
    ElMessage.success('更新医生成功')
    return response.data
  } catch (error) {
    ElMessage.error('更新医生失败')
    throw error
  }
}

/**
 * 删除医生
 * @param id 医生ID
 */
export const deleteDoctor = async (id: number): Promise<void> => {
  try {
    await request.delete(`/api/doctors/${id}`)
    ElMessage.success('删除医生成功')
  } catch (error) {
    ElMessage.error('删除医生失败')
    throw error
  }
}

/**
 * 切换医生状态
 * @param id 医生ID
 * @param delFlag 状态标记
 */
export const toggleDoctorStatus = async (id: number, delFlag: 'Y' | 'N'): Promise<void> => {
  try {
    await request.patch(`/api/doctors/${id}/status`, { delFlag })
    ElMessage.success('状态更新成功')
  } catch (error) {
    ElMessage.error('状态更新失败')
    throw error
  }
}

// 缓存最近请求的医生数据
const doctorCache = new Map<number, Doctor>()

/**
 * 获取医生详情（带缓存）
 * @param id 医生ID
 * @param forceRefresh 是否强制刷新缓存
 * @returns 医生详情
 */
export const getDoctorWithCache = async (id: number, forceRefresh = false): Promise<Doctor> => {
  if (!forceRefresh && doctorCache.has(id)) {
    return doctorCache.get(id)!
  }

  const doctor = await getDoctor(id)
  doctorCache.set(id, doctor)
  return doctor
}
